<template>
  <div class="role">
    <!-- 新增角色 -->
    <el-dialog
      width="500px"
      custom-class="customWidth"
      center
      :before-close="closeDialog"
      title="新增角色"
      :close-on-click-modal="false"
      :visible.sync="addDialogFormVisible"
    >
      <el-form
        :model="addataForm"
        :rules="addataRule"
        ref="addataForm"
        @keyup.enter.native="addataFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="角色名" prop="name">
          <el-col :span="18">
            <el-input v-model="addataForm.name" placeholder="角色名称" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleifo">
          <el-col :span="18">
            <el-input v-model="addataForm.roleifo" placeholder="角色描述" type="textarea"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-col :span="18">
            <div class="tree">
              <el-tree
                :data="treedata"
                show-checkbox
                ref="tree"
                node-key="id"
                highlight-current
                :default-expand-all="false"
                :props="defaultProps"
              ></el-tree>
            </div>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addvisible ()">取消</el-button>
        <el-button type="primary" @click="addataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog
      width="500px"
      custom-class="customWidth"
      center
      title="修改角色"
      :close-on-click-modal="false"
      :visible.sync="editDialogFormVisible"
    >
      <el-form
        :model="editdataForm"
        :rules="editdataRule"
        ref="editdataForm"
        @keyup.enter.native="editdataFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="角色名" prop="name">
          <el-col :span="18">
            <el-input v-model="editdataForm.name" placeholder="角色名称" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleifo">
          <el-col :span="18">
            <el-input v-model="editdataForm.roleifo" placeholder="角色描述" type="textarea"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-col :span="18">
            <div class="tree">
              <el-tree
                :data="treedataup"
                show-checkbox
                ref="tree"
                node-key="id"
                highlight-current
                :props="defaultProps"
              ></el-tree>
            </div>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editvisible()">取消</el-button>
        <el-button type="primary" @click="editataFormSubmit()" :disabled="editcofrom">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      row: [],
      expand: [],
      editcofrom: true,
      addataForm: {
        name: "",
        roleifo: "",
        rolelist: [],
      },
      editdataForm: {
        name: "",
        roleifo: "",
        rolelist: [],
      },
      idArr: [],
      treedataup: [],
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      addataRule: {
        name: [{ required: true, message: "角色名不能为空", trigger: "blur" }],
      },
      editdataRule: {
        name: [{ required: true, message: "角色名不能为空", trigger: "blur" }],
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  props: ["treedata", "userGuid"],
  watch: {
    addDialogFormVisible(val) {},
  },
  mounted() {},

  created() {
    this.unitGuid = this.$store.state.user.changeschoolid;
  },
  methods: {
    isExpand() {
      return false;
    },
    //获取递归id
    getId(roledatas) {
      roledatas.forEach((ele) => {
        if (ele.children.length == 0 && ele.flag == true) {
          this.idArr.push(ele.id);
        }
        if (ele.children.length != 0) {
          this.getId(ele.children);
        }
      });
    },
    //默认展开
    expandid(roledatas) {
      roledatas.forEach((ele) => {
        if (ele.children.length != 0 && ele.flag == true) {
          let expandid = ele.id.toString();
          this.expand.push(expandid);
        }
        console.log(this.expand);
      });
    },
    //角色查询权限
    checkrole(val) {
      this.$http({
        url: this.$http.adornUrl("/sys/get-permission-tree"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            roleId: val,
            userGuid: this.userGuid,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        //  console.log(data)
        if (data.messageCode === 200) {
          this.treedataup = data.messageContent;
          this.getId(this.treedataup);
          // this.expandid(this.treedataup)
          this.editcofrom = false;
          // console.log(this.idArr)
          this.$refs.tree.setCheckedKeys(this.idArr);
          return;
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    //清空树状
    resetChecked() {
      this.$refs.tree.setCheckedKeys([]); // CheckedArr 一个选中的数组element Ui的东西，关键是看$nextTick的用法
    },
    getCheckedKeysto() {
      // console.log(this.$refs.tree.getCheckedKeys());
      return this.$refs.tree.getCheckedKeys();
    },
    getparentArrid() {
      return this.$refs.tree.getHalfCheckedKeys();
    },
    // 表格提交
    addataFormSubmit() {
      this.$refs["addataForm"].validate((valid) => {
        let parentArr = [];
        let childeArr = [];
        parentArr = this.getparentArrid();
        childeArr = this.getCheckedKeysto();
        this.addataForm.rolelist = parentArr.concat(childeArr);
        console.log(this.addataForm);
        if (this.addataForm.rolelist.length == 0) {
          this.$message({
            message: "请分配角色权限",
            type: "warning",
          });
          return false;
        }
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sys/add-system-role"),
            method: "post",
            data: this.$http.adornData({
              messageContent: {
                name: this.addataForm.name,
                operationGuid: this.userGuid,
                permissionId: this.addataForm.rolelist,
                roleDescription: this.addataForm.roleifo,
                unitGuid: this.unitGuid,
              },
              messageType: 0,
            }),
          }).then(({ data }) => {
            console.log(data);
            if (data.messageCode == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
              this.addDialogFormVisible = false;
              this.treedata = [];
              this.init();
            } else {
              this.$message.error(data.errorMessage);
            }
          });
        }
      });
    },
    //获取树状图节点
    handleCheckChange() {
      let res = this.$refs.tree.getCheckedNodes();
      let arr = [];
      res.forEach((item) => {
        arr.push(item.id);
      });
      return arr;
    },
    addinit() {
      this.data = this.treedata;
      this.addDialogFormVisible = true;
    },
    addvisible() {
      this.addDialogFormVisible = false;
      this.$refs["addataForm"].resetFields();
      this.resetChecked();
    },
    editinit(row) {
      console.log(row);
      this.row = row;
      this.editDialogFormVisible = true;
      this.editdataForm.name = row.name;
      this.editdataForm.pkRoleId = row.pkRoleId;
      this.editdataForm.roleifo = row.roleDescription;
      this.editdataForm.unitGuid = row.unitGuid;
      this.editcofrom = true;
      this.$nextTick(() => {
        this.resetChecked();
        this.idArr = [];
        setTimeout(() => {
          this.checkrole(row.pkRoleId);
        }, 100);
      });
    },
    editvisible(row, val) {
      this.editDialogFormVisible = false;
    },
    //确认修改
    editataFormSubmit() {
      this.$refs["editdataForm"].validate((valid) => {
        let parentArr = [];
        let childeArr = [];
        parentArr = this.getparentArrid();
        childeArr = this.getCheckedKeysto();
        this.editdataForm.rolelist = parentArr.concat(childeArr);
        console.log(this.editdataForm.rolelist);
        if (this.editdataForm.rolelist.length == 0) {
          this.$message({
            message: "请分配角色权限",
            type: "warning",
          });
          return false;
        }
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sys/update-system-role"),
            method: "post",
            data: this.$http.adornData({
              messageContent: {
                name: this.editdataForm.name,
                operationGuid: this.userGuid,
                permissionId: this.editdataForm.rolelist,
                roleDescription: this.editdataForm.roleifo,
                pkRoleId: this.editdataForm.pkRoleId,
                unitGuid: this.editdataForm.unitGuid,
              },
              messageType: 0,
            }),
          }).then(({ data }) => {
            console.log(data);
            if (data.messageCode == 200) {
              this.$message({
                message: "修改成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.editDialogFormVisible = false;
                  this.$emit("refreshDataList");
                  this.$emit("refrolelist", this.row);
                },
              });
              this.editDialogFormVisible = false;
            } else {
              this.$message.error(data.errorMessage);
            }
          });
        }
      });
    },
    closeDialog(done) {
      this.$refs["addataForm"].resetFields();
      this.resetChecked();
      done();
    },
    //初始化
    init() {
      this.$nextTick(() => {
        this.$refs["addataForm"].resetFields();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tree {
  min-width: 100%;
  font-size: 14px;
  display: inline-block;
  overflow: hidden;
}
.role{
/deep/.el-dialog--center .el-dialog__body{
  padding: 0;
  padding-left:75px;
}
// 树状图选中样式
.el-tree--highlight-current /deep/ .el-tree-node.is-checked>.el-tree-node__content {
  background-color: #fff;
  // color:#00ff7f;
}

.el-tree--highlight-current /deep/ .el-tree-node.is-current>.el-tree-node__content {
  background-color: #fff;
  //  color:#00ff7f;
}
}

.tree {
  overflow-y: scroll;
  overflow-x: auto;
  height: 30vh;
      //滚动条的宽度
    &::-webkit-scrollbar {
      width: 10;
      height: 10;
    }
    //滚动条的滑块
    &::-webkit-scrollbar-thumb {
      background-color: #a1a3a9;
      border-radius: 3px;
    }
  /*width:200px;*/
  // border: 1px solid blue;
}
.el-dialog__wrapper {
}
</style>